﻿(function ($) {
    /* Defaults */
    var defaults = {
        width: 800,
        height: 600,
        onsuccess: null,
        oncancel: null,
        sender: null,
        url: '',
        title: null,
        maxWidth: $(document).width() - 50,
        maxHeight: $(document).height() - 50,
        pageunload: null,
        returnValue: ''
    };

    /* Public Methods */

    $.iFramePopup = function (options) {
        showPopup(options);
    };

    $.iFramePopup.ModalStack = [];

    $.iFramePopup.zIndex = 10000;

    $.iFramePopup.GUIDPrefix = "ifr_";
    $.iFramePopup.CurrentId = 0;

    $.iFramePopup.CompletePopup = function (val, isClose) {
        isClose = isClose || true;
        var guid = getParameterByName('if_guid');
        if (guid) {
            window.parent.$(window.parent.document).trigger('iFramePopup_Complete', { guid: guid, value: val, isClose: isClose });
        }
    };

    $.iFramePopup.ClosePopup = function () {
        var guid = getParameterByName('if_guid');
        if (guid) {
            window.parent.$(window.parent.document).trigger('iFramePopup_Close', { guid: guid });
        }
        else {
            window.close();
        }
    };

    $.iFramePopup.SetReturnValue = function (value) {
        var guid = getParameterByName('if_guid');
        if (guid) {
            window.parent.$(window.parent.document).trigger('iFramePopup_SetReturnValue', { guid: guid, value: value });
        }
    };

    /* Events */
    $(document).on("iFramePopup_Complete", function (event, param) {
        var modalOpt = $.iFramePopup.ModalStack[param.guid];
        if (modalOpt && modalOpt.onsuccess) {
            //if (spinner) spinner.start();
            try {
                // to fix IE issue - spinner not clossing.
                modalOpt.onsuccess(param.value, modalOpt.sender);
            }
            catch (e) { }
            finally {
                //if (spinner) spinner.stop();
            }
        }

        if (param.isClose) {
            if (validateBeforeClose(param.guid)) {
                closePopup(param.guid);
            }
        }
    });

    $(document).on("iFramePopup_Close", function (event, param) {
        if (validateBeforeClose(param.guid)) {
            $("#" + param.guid).dialog('close');
        }
    });

    $(document).on("iFramePopup_OpenPopup", function (event, param) {
        showPopup(param.options);
    });

    $(document).on("iFramePopup_SetReturnValue", function (event, param) {
        var modalOpt = $.iFramePopup.ModalStack[param.guid];
        if (modalOpt) {
            modalOpt.returnValue = param.value;
        }
    });

    /* Private Methods */

    // Show iframe popup
    function showPopup(options) {
        if (!isIframePopup()) {
            options = $.extend({}, defaults, options);
            options.title = options.title || getParameterByName('title', options.url);

            var guid = generateGUID();
            if (options.width > options.maxWidth) {
                options.width = options.maxWidth;
            }

            if (options.height > options.maxHeight) {
                options.height = options.maxHeight;
            }

            var html = '<div class="dialog" id="' + guid + '">' +
                            '<div class="ifrmLoader">' +
                                '<table><tr>' + 
	                                '<td class="loadImg"><span></span></td>' + 
                                    '<td class="loadTxt">Loading...</td>' + 
                                '</tr></table>' +
                            '</div>' + 
                            '<iframe width="' + options.width + '" height="' + options.height + '" scrolling="yes"></iframe>' +
                        '</div>';
            $('body').append(html);

            var popup = $("#" + guid);

            popup.dialog({
                autoOpen: false,
                show: "fade",
                hide: "fade",
                modal: true,
                open: function (ev, ui) {
                    increaseZIndex(ev.target, guid);
                    var popupUrl = options.url;
                    if (getParameterByName('if_guid', popupUrl)) {
                        popupUrl = popupUrl.replace(/(if_guid=)[^\&]+/, '$1' + guid);
                    }
                    else {
                        var urlParts = popupUrl.split('#');
                        var mainUrl = urlParts[0];
                        var anchorTag = '';
                        if (urlParts.length > 1) {
                            anchorTag = "#" + urlParts[1];
                        }

                        popupUrl = mainUrl + '&if_guid=' + guid + anchorTag;
                    }

                    $('iframe', ev.target)
                        .attr('src', popupUrl)
                        .load(function () {
                            $('.ifrmLoader', ev.target).fadeOut('fast');
                            options.pageunload = $(this).get(0).contentWindow.onbeforeunload;
                        });
                },
                close: function (ev, ui) {
                    closePopup($(ev.target).attr('id'), true);
                },
                beforeClose: function (ev, ui) {
                    return validateBeforeClose($(ev.target).attr('id'));
                },
                height: 'auto',
                width: 'auto',
                resizable: true,
                dialogClass: 'no-close jPopup',
                title: options.title
            });

            $.iFramePopup.ModalStack[guid] = options;
            popup.dialog("open");
            popup.dialog("moveToTop");
        }
        else {
            openPopupFromParentPage(options);
        }
    }

    // Close iframe popup
    function closePopup(guid, fireCallback) {
        var modalOpt = $.iFramePopup.ModalStack[guid];
        if (fireCallback) {
            if (modalOpt && modalOpt.oncancel) {
                //if (spinner) spinner.start();
                try {
                    modalOpt.oncancel(modalOpt.returnValue, modalOpt.sender);
                } catch (e) { }
                finally {
                    //if (spinner) spinner.stop();
                }
            }
        }

        delete $.iFramePopup.ModalStack[guid];

        // stop throwing errors, when we remove iframe while page loaded. (first load 'about:black', then remove iframe)
        var frame = $('#' + guid).find('iframe').get(0);
        var frameDoc = frame.contentDocument || frame.contentWindow.document;
        frame.scr = "about:black";
        frameDoc.write('');
        frameDoc.close();
        $(frame).remove();
        $('#' + guid).html('').dialog('destroy').remove();

        if (typeof CollectGarbage == "function") {
            CollectGarbage();
        }
    };

    // Validate Close iframe popup
    function validateBeforeClose(guid) {
        var modalOpt = $.iFramePopup.ModalStack[guid];
        if (modalOpt.pageunload) {
            var text = modalOpt.pageunload();
            if (text && !confirm(text + "\n\n Are you sure you want to leave this page?")) {
                return false;
            }

            $("#" + guid + " iframe").get(0).contentWindow.onbeforeunload = null;
        }

        return true;
    }


    // generate GUID for popups
    function generateGUID() {
        if (!$.iFramePopup.CurrentId || $.iFramePopup.CurrentId <= 0) {
            $.iFramePopup.CurrentId = 0;
            var idList = [];
            $('div.iFramePopup div.ui-dialog-content[id$="' + $.iFramePopup.GUIDPrefix + '"]').each(function () {
                var id = this.id.toString().substring($.iFramePopup.GUIDPrefix.length);
                idList.push(id);
            });

            if (idList.length > 0) {
                $.iFramePopup.CurrentId = Math.max.apply(Math, idList);
            }
        }

        $.iFramePopup.CurrentId = $.iFramePopup.CurrentId + 1;
        return $.iFramePopup.GUIDPrefix + $.iFramePopup.CurrentId;
    };

    // read query string parameter
    function getParameterByName(name, url) {
        url = url || location.search;
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(url);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };

    // check whether js is loaded inside iframe popup 
    function isIframePopup() {
        var guid = getParameterByName('if_guid');
        if (guid) {
            return true;
        }
        return false;
    };

    // open iframe popup from main page (prevent popup loading inside another popup)
    function openPopupFromParentPage(options) {
        window.parent.$(window.parent.document).trigger('iFramePopup_OpenPopup', { options: options });
    };

    // increace zindex of popup to stop interfering with other UI elements (specially in strata) 
    function increaseZIndex(popup, guid) {
        var popupBox = $(popup).closest('div[aria-describedby="' + guid + '"]');
        var popupLayout = popupBox.prev('.ui-widget-overlay');

        popupBox.css('z-index', $.iFramePopup.zIndex + 1);
        popupLayout.css('z-index', $.iFramePopup.zIndex);

        $.iFramePopup.zIndex = $.iFramePopup.zIndex + 2;
    };
}(jQuery));

